package com.xianyun.site.auth.service.impl;

import com.xianyun.common.core.utils.StringUtils;
import com.xianyun.site.auth.service.execute.AuthUserLoginQueryExo;
import com.xianyun.site.auth.service.execute.SystemBaseLoginQueryExo;
import com.xianyun.site.auth.common.token.IAuthenticationToken;
import com.xianyun.site.auth.service.IUserDetailsService;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.model.AuthUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * 第三方登录获取用户信息的默认实现，兼容了 JustAuth。
 * <p>有特殊需求可以继承 ExtendUserDetailsService，并使其子类成为 spring bean</p>
 *
 * @author songyinyin
 * @date 2020/5/5 下午 05:14
 */
@Slf4j
@Component
public class IUserDetailsServiceImpl implements IUserDetailsService {

    @Autowired
    private SystemBaseLoginQueryExo systemBaseLoginQueryExo;

    @Autowired
    private AuthUserLoginQueryExo authUserLoginQueryExo;

    /**
     * 扩展第三方登录
     */
    @Override
    public UserDetails loadUserByExtendKey(IAuthenticationToken token) throws UsernameNotFoundException {
        if (!(null!=(token.getPrincipal()) && StringUtils.isNotEmpty(token.getPrincipal().toString())
                && token.getPrincipal() instanceof AuthUser)) {
            return systemBaseLoginQueryExo.execute(token);
        }
        AuthUser authUser = (AuthUser) token.getPrincipal();
        log.info(authUser.toString());
        return authUserLoginQueryExo.execute(authUser,token.getRequest().getSession().getId());
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return null;
    }
}
